var APP = require("../../../lib/main/app");
var VALIDATE = require("../../../lib/function/validate");
var UTIL = require("../../../lib/function/util");
var USER = require("../../../lib/module/user");
var Config = require("../../../lib/config/config");

var page = {
    subject: null,
	activeIndex:0,
	footerHeight:null,
	xyType:'user',
	zknightCode:null,
	checkTime:null,//倒计时
	device_id:'ces',//设备id
	codeId:'',//二维码id
	language:'cn',
    ready : function() {
        var that = this;
		var language = navigator.language
		try{
			let _txt = language.split('-')[0];
			if(_txt == 'zh'){
				that.language = 'cn'
			}else{
				that.language = 'en'
			}
		}catch(e){
			//TODO handle the exception
		}
		var winHeight = api.winHeight;
		if(winHeight < 1070){
			$('.login-con').addClass('active');
		}else{
			$('.login-con').removeClass('active');
		}
		// 头部处理
		var headerHeight = $('#header').height();
		$('body').css('padding-top', headerHeight);
		
		// var F_Account = API.getStorage('F_Account');
		var F_Account = api.getPrefs({
		   sync: true,
		   key: 'F_Account'
		});
		// var F_Password = API.getStorage('F_Password');
		var F_Password = api.getPrefs({
		   sync: true,
		   key: 'F_Password'
		});
		
		if(F_Account) {
			$("[name='mobile']").val(F_Account);
		}
		if(F_Password) {
			$("[name='mobile-psd']").val(F_Password);
		}
		//传入展示图形验证码位置的ID,若只传ID，则其他参数使用默认值
		that.zknightCode = new zknightH5imagecaptcha("captcha");
		
		
		// 设置语言
		let lang =  api.getGlobalData({key: 'lang'});
		if(!lang){
			api.setGlobalData({
			    key: 'lang',
			    value: that.language
			});
		}else{
			that.language = lang;
		}
		if(that.language == 'cn'){
			$('.chinese').addClass('active').siblings().removeClass('active');
		}else{
			$('.english').addClass('active').siblings().removeClass('active');
		}
		i18n("[i18n]", {
			lang: that.language,// 变更语言
			filePath: "i18n/",
			get: true
		});
		
		i18n("[i18n]", {
			defaultLang: that.language, // 设置默认语言，
			filePath: "i18n/",
			filePrefix: "i18n_",
			fileSuffix: "",
			forever:true,// 默认为 true  保存当前语言，设置为 false 后，每次刷新都为cn 
			get: true,
			only: ['value', 'html', 'placeholder', 'title'], // 全局设置i18n-only，默认值：['value', 'html', 'placeholder', 'title']
			callback: function() {
				console.log("i18n is ready.");
			}
		});
		
		
    },
    on : function() {
		var that = this;
		// 赋值账号密码
		API.listenEvt('LOGOUT', function() {
			var F_Account = api.getPrefs({
		   sync: true,
		   key: 'F_Account'
		});
		var F_Password = api.getPrefs({
		   sync: true,
		   key: 'F_Password'
		});
			
			if(F_Account) {
				$("[name='mobile']").val(F_Account);
			}
			
			if(F_Password) {
				$("[name='mobile-psd']").val(F_Password);
			}
		});
		//首页点击返回
		API.listenEvt('keyback', function() {
			let msg = i18n.get("exit.app") || '再点一次退出应用';
			api.toast({
		        msg : msg,
		        duration : 2000,
		        location : 'bottom'
		    });
		    API.listenEvt('keyback', function() {
		    	api.closeWidget({
		            silent : true
		        });
		    });
		});
		var events = [
			//打开页面
			['.openPage', function() {
				var _url = $(this).data('url');
				let toast = i18n.get("system.under.development") || '系统开发中...';
				if (_url) {
					APP.w.openWin(_url);
				} else {
					API.errorToast(toast);
				}
			}],
			
			// 切换为扫码登录
			['.pwd-con .codelogin', function() {
				that.createLogin();
				that.checkTime = setInterval(function(){
					that.checkLogin();
				},1000)
				$('.pwd-con').hide();
				$('.code-con').show();
			}],
			// 切换为密码登录
			['.code-con .return', function() {
				clearInterval(that.checkTime);
				$('.code-con').hide();
				$('.pwd-con').show();
			}],
			// 切换为英文
			['.english', function() {
				i18n("[i18n]", {
					lang: "en",// 变更语言
					filePath: "i18n/",
					get: true
				});
				api.setGlobalData({
				    key: 'lang',
				    value: 'en'
				});
				$(this).addClass('active').siblings().removeClass('active');
				console.log("中文===============")
				console.log(i18n.get("footer.about"));
			}],
			// 切换为中文
			['.chinese', function() {
				i18n("[i18n]", {
					lang: "cn",// 变更语言
					filePath: "i18n/",
					get: true
				});
				api.setGlobalData({
				    key: 'lang',
				    value: 'cn'
				});
				$(this).addClass('active').siblings().removeClass('active');
				console.log("中文===============")
				console.log(i18n.get("footer.about"));
			}],
		];
		APP.e.more(events);
		//提交表单
		$(document).on('click','#login-sub',function(){
			var _Phone = $(".phone").val();
			var _Password = $(".password").val();
			var _code = $(".form-lis-code .code").val();
			let toast1 = i18n.get("mobile.empty") || '手机号不能为空！';
			let toast2 = i18n.get("mobile.error") || '请输入正确的手机号！';
			let toast3 = i18n.get("password.empty") || '密码不能为空！';
			if(!_Phone){
				API.errorToast(toast1);
				return;
			}
			if(!checkPhone(_Phone)){
				API.errorToast(toast2);
				return false;
			}
			if(!_Password){
				API.errorToast(toast3);
				return false;
			}
			if(!_code){
				// API.errorToast('验证码不能为空！');
				// return false;
			}
			
			//文本框输入的验证码
			var zknightInputCode = document.getElementById("code").value;
			//传入输入的验证码，返回验证结果
			var result = that.zknightCode.validate(zknightInputCode);
			var postData = {
				account: _Phone,
				password: _Password,
			}
			that.loginUp(postData);
			
			// if(!result){
			// 	var postData = {
			// 		account: _Phone,
			// 		password: _Password,
			// 	}
			// 	that.loginUp(postData);
			// }else{
			// 	API.errorToast('验证码错误！');
			// }
		})
		//检查手机
		var checkPhone = function(val) {
		  	var pattern = /^1[3456789]\d{9}$/;
		  	return pattern.test(val);
		};
		//批量事件end
		
		//监听手机号并验证
		$('#mobile').bind('input propertychange', function() {});
		window.onresize = () => {
			var winHeight = api.winHeight;
		  if(winHeight < 1070){
		  	$('.login-con').addClass('active');
		  }else{
			$('.login-con').removeClass('active');
		  }
		}
    },
    methods : {
		
		//检测扫码登录 device/check_login
		checkLogin: function(){
			var that = this;
			var postData = {
				id: that.codeId,
			}
			APP.r.post({
				api: 'device/check_login',
				params: postData,
				success: function(res) {
					// 1 未扫码 2已扫码未确定 3已扫码确定登录
					if(res.data.status == 3){
						
						clearInterval(that.checkTime)
						USER.setUserToken(res.data.token);//缓存token
						that.getUserInfo()
					}
				}
			});
			
		},
		//获取用户信息
		getUserInfo: function(){
			var that = this;
			APP.r.post({
				api: 'user/get_user_info',
				params: {},
				success: function(res) {
					USER.setUserinfo(res.data.userinfo);
					USER.setUserToken(res.data.userinfo.token);//缓存token
					let _txt = i18n.get("login.succeeded") || '登录成功';
					API.successToast(_txt, function() {
						$('.code-con').hide();
						$('.pwd-con').show();
						API.sendEvt('LOGIN_SUCCESS');
					    APP.w.openWin("index_main");
					});
				}
			});
		},
		// 获取二维码
		createLogin: function(){
			var that = this;
			var _params = {
				device_id: that.device_id,
			}
			APP.r.post({
				api: 'device/create_login',
				params: _params,
				success: function(ret) {
					var _img = Config.imgHost + ret.data.url;
					that.codeId =  ret.data.id;
					$('.login-code img').attr('src',_img);
				}
			});
		},
		// 密码登录
		loginUp: function(postData){
			var that = this;
			APP.r.post({
				api: 'user/login',
				params: postData,
				success: function(res) {
					// API.setStorage(APP.Key.user_token, res.data.token);
					USER.setUserinfo(res.data.userinfo);
					USER.setUserToken(res.data.userinfo.token);//缓存token
					API.sendEvt('LOGIN_SUCCESS');
					let _txt = i18n.get("login.succeeded") || '登录成功';
					API.successToast(_txt, function() {
					    APP.w.openWin("index_main");
						// $("[name='mobile']").val('');
						// $("[name='mobile-psd']").val('');
						// $("[name='code']").val('');
					});
				}
			});
		},
    }
}
API.run(page);

